from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from utils.send_message import send_message
from utils.get_month_list import get_month_range
from .models import *
from .serializers import *
import datetime
import redis
import re
import time


# 获取短信验证码
class Getphonecode(APIView):
    def get(self,request):
        phone = request.query_params.get("phone")
        resp = send_message(phone)
        if resp["statusCode"] == "000000" or resp["statusCode"] == "112310" or resp["statusCode"] == "172001":
            return Response({'msg': "发送短信验证码成功", "code": 200})
        else:
            return Response({'msg': "发送短信验证码失败", "code": 400})
# 用户登录
class Login(APIView):
    def post(self,request):
        phone = request.data.get("phone")
        code = request.data.get("code")
        if python == "13462336969" and code == "971024":
            user = User.objects.get(phone=phone)
            data = UserSer(user).data
            return Response({"msg": "登录成功", "code": 200, "data": data})
        client = redis.Redis(db=2)
        redis_code = client.get("sms_%s" % phone)
        if not redis_code:
            return Response({"msg": "验证码过期", "code": 400})
        sms_code = str(client.get("sms_%s" % phone),encoding="utf-8")
        if sms_code != code:
            return Response({"msg": "验证码错误", "code": 400})
        user_num = User.objects.filter(phone=phone).count()
        if user_num == 0:
            username = phone[:3]+"****"+phone[7:]
            User.objects.create(phone=phone,username= username)
        elif user_num > 1:
            return Response({"msg":"用户信息重复","code":400})
        user = User.objects.get(phone=phone)
        data = UserSer(user).data
        return Response({"msg":"登录成功","code":200,"data":data})

# 体重信息写入
class WriteWeight(APIView):
    def post(self,request):
        user_id = request.data.get("user_id")
        weight = request.data.get("weight")
        if not all([user_id,weight]):
            return Response({"msg": "信息为空，请输入后再提交", "code": 401})
        if not bool(re.match("^([1-9]\d{0,2}|0)([.]?|(\.\d{1,2})?)$", weight)):
            return Response({"msg": "数据格式不正确,", "code": 401})
        Weight.objects.create(user_id=user_id,weight=weight)
        return Response({"msg":"信息写入成功","code":200})
# 体重最大值最小值设置
class ShezhiWeight(APIView):
    def post(self,request):
        user_id = request.data.get("user_id")
        min_weight = request.data.get("min")
        max_weight = request.data.get("max")
        if not all([user_id,min_weight,max_weight]):
            return Response({"msg": "信息为空，请输入后再提交", "code": 401})
        user = User.objects.get(id=user_id)
        user.max_weight = max_weight
        user.min_weight = min_weight
        user.save()
        return Response({"msg":"信息写入成功","code":200})
# 体重信息查询
class GetWeight(APIView):
    def get(self,request):
        user_id = request.query_params.get("user_id")
        num = request.query_params.get("num")
        if num == "":
            n = 15
        else:
            if num.isdigit():
                n = int(num)
            else:
                return Response({"msg": "输入信息格式错误，请输入正整数", "code": 401})
        weight = Weight.objects.filter(user_id=user_id).order_by("-id")[:n]
        data = WeightSer(weight,many=True).data
        timedata = []
        for i in weight:
            timedata.append(i.create_time)
        weightdata = []
        for i in weight:
            weightdata.append(i.weight)
        timedata.reverse()
        weightdata.reverse()
        user = User.objects.get(id=user_id)
        min_weight = user.min_weight
        max_weight = user.max_weight
        return Response({"msg": "获取成功成功", "code": 200, "data": data,"timedata":timedata,"weightdata":weightdata,"min_weight":min_weight,"max_weight":max_weight})

# 资产信息写入
class WriteZichan(APIView):
    def post(self,request):
        user_id = request.data.get("user_id")
        zhifubao = request.data.get("zhifubao")
        weixin = request.data.get("weixin")
        yinhangka = request.data.get("yinhangka")
        touzi = request.data.get("touzi")
        huabei = request.data.get("huabei")
        if not all([user_id,zhifubao,weixin,yinhangka,touzi]):
            return Response({"msg": "信息为空，请输入后再提交", "code": 401})
        if not bool(re.match("^([1-9]\d{0,7}|0)([.]?|(\.\d{1,2})?)$", zhifubao)):
            return Response({"msg": "支付宝数据格式不正确,", "code": 401})
        if not bool(re.match("^([1-9]\d{0,7}|0)([.]?|(\.\d{1,2})?)$", weixin)):
            return Response({"msg": "微信数据格式不正确,", "code": 401})
        if not bool(re.match("^([1-9]\d{0,7}|0)([.]?|(\.\d{1,2})?)$", yinhangka)):
            return Response({"msg": "银行卡数据格式不正确,", "code": 401})
        if not bool(re.match("^([1-9]\d{0,7}|0)([.]?|(\.\d{1,2})?)$", touzi)):
            return Response({"msg": "投资数据格式不正确,", "code": 401})
        if not bool(re.match("^([1-9]\d{0,7}|0)([.]?|(\.\d{1,2})?)$", huabei)):
            return Response({"msg": "花呗数据格式不正确,", "code": 401})
        money = float(zhifubao) + float(weixin) + float(yinhangka) + float(touzi) - float(huabei)
        Zichan.objects.create(user_id=user_id,
                              zhifubao=zhifubao,
                              weixin=weixin,
                              yinhangka=yinhangka,
                              touzi=touzi,
                              huabei=huabei,
                              money=money)
        return Response({"msg":"信息写入成功","code":200})
# 资产信息查询
class GetZichan(APIView):
    def get(self,request):
        user_id = request.query_params.get("user_id")
        num = request.query_params.get("num")
        if num == "":
            n = 15
        else:
            if num.isdigit():
                n = int(num)
            else:
                return Response({"msg": "输入信息格式错误，请输入正整数", "code": 401})
        zichan = Zichan.objects.filter(user_id=user_id).order_by("-id")[:n]
        data = ZichanSer(zichan,many=True).data
        timedata = []
        for i in zichan:
            timedata.append(i.create_time)
        moneydata = []
        for i in zichan:
            moneydata.append(i.money)
        timedata.reverse()
        moneydata.reverse()
        return Response({"msg": "获取成功成功", "code": 200, "data": data,"timedata":timedata,"moneydata":moneydata})

# 投资信息写入
class WriteTouzi(APIView):
    def post(self,request):
        user_id = request.data.get("user_id")
        start_money = request.data.get("start_money")
        type = request.data.get("type")
        postscript = request.data.get("postscript")
        if not all([user_id,start_money,type,postscript]):
            return Response({"msg": "信息为空，请输入后再提交", "code": 401})
        if not bool(re.match("^([1-9]\d{0,7}|0)([.]?|(\.\d{1,2})?)$", start_money)):
            return Response({"msg": "投资金额数据格式不正确,", "code": 401})
        Touzi.objects.create(user_id=user_id,
                             start_money=start_money,
                             type=type,
                             postscript=postscript
                            )
        return Response({"msg":"信息写入成功","code":200})
# 投资信息更新
class UpdateTouzi(APIView):
    def post(self,request):
        id = request.data.get("id")
        end_money = request.data.get("end_money")
        if not bool(re.match("^([1-9]\d{0,7}|0)([.]?|(\.\d{1,2})?)$",end_money)):
            return Response({"msg": "数据格式不正确,", "code": 401})
        touzi = Touzi.objects.get(id=id)
        touzi.end_money = end_money
        touzi.end_time = datetime.datetime.now()
        touzi.statue = 1
        touzi.shouyi = float(end_money) - float(touzi.start_money)
        touzi.shouyilv = (float(end_money) - float(touzi.start_money))/float(touzi.start_money)
        # 获取时间转化为元组，列表
        a = list(datetime.datetime.now().timetuple())
        b = list(touzi.start_time.timetuple())
        userEnd = datetime.datetime(a[0], a[1], a[2])
        userStart = datetime.datetime(b[0], b[1], b[2])
        # 写入时间
        touzi.sum_time = (userEnd - userStart).days
        touzi.save()
        return Response({"msg": "数据写入成功", "code": 200})
# 投资信息查询
class GetTouzi(APIView):
    def get(self,request):
        user_id = request.query_params.get("user_id")
        type = request.query_params.get("type")
        if type == "已买入":
            touzi = Touzi.objects.filter(user_id=user_id,statue=0).order_by("-id")[:15]
        elif type == "已卖出":
            touzi = Touzi.objects.filter(user_id=user_id,statue=1).order_by("-id")[:15]
        else:
            touzi = Touzi.objects.filter(user_id=user_id).order_by("-id")[:15]
        data = TouziSer(touzi,many=True).data
        namedata = []
        for i in touzi:
            namedata.append(i.postscript)
        moneydata = []
        for i in touzi:
            moneydata.append(i.start_money)
        lilvdata = []
        for i in touzi:
            lilvdata.append(i.shouyilv)

        namedata.reverse()
        moneydata.reverse()
        lilvdata.reverse()
        return Response({"msg": "获取成功成功", "code": 200, "data": data,"namedata":namedata,"moneydata":moneydata,"lilvdata":lilvdata})

# 流水信息写入
class WriteLiushuiZhifubao(APIView):
    def post(self,request):
        user_id = request.data.get("user_id")
        month = request.data.get("month")
        zhifubao = request.data.get("zhifubao")
        if not all([user_id,month,zhifubao]):
            return Response({"msg": "信息为空，请输入后再提交", "code": 401})
        if not bool(re.match("^([1-9]\d{0,7}|0)([.]?|(\.\d{1,2})?)$", zhifubao)):
            return Response({"msg": "数据格式不正确,", "code": 401})
        num = Liushui.objects.filter(user_id=user_id,month=month).count()
        if num == 0:
            Liushui.objects.create(user_id=user_id,month=month,zhifubao=zhifubao)
        elif num == 1:
            liushui = Liushui.objects.get(user_id=user_id,month=month)
            liushui.zhifubao = zhifubao
            liushui.money = float(liushui.weixin) + float(zhifubao)
            liushui.statue = 1
            liushui.save()
        else:
            return Response({"msg": "信息重复，请查看后台", "code": 402})
        return Response({"msg":"信息写入成功","code":200})
class WriteLiushuiWeixin(APIView):
    def post(self,request):
        user_id = request.data.get("user_id")
        month = request.data.get("month")
        weixin = request.data.get("weixin")
        if not all([user_id,month,weixin]):
            return Response({"msg": "信息为空，请输入后再提交", "code": 401})
        if not bool(re.match("^([1-9]\d{0,7}|0)([.]?|(\.\d{1,2})?)$", weixin)):
            return Response({"msg": "数据格式不正确,", "code": 401})
        num = Liushui.objects.filter(user_id=user_id,month=month).count()
        if num == 0:
            Liushui.objects.create(user_id=user_id,month=month,weixin=weixin)
        elif num == 1:
            liushui = Liushui.objects.get(user_id=user_id,month=month)
            liushui.weixin = weixin
            liushui.money = float(liushui.zhifubao) + float(weixin)
            liushui.statue = 1
            liushui.save()
        else:
            return Response({"msg": "信息重复，请查看后台", "code": 402})
        return Response({"msg":"信息写入成功","code":200})
# 流水信息查询
class GetLiushui(APIView):
    def get(self,request):
        user_id = request.query_params.get("user_id")
        num = request.query_params.get("num")
        # 判断信息数量
        if num == "":
            n = 15
        else:
            if num.isdigit():
                n = int(num)
            else:
                return Response({"msg": "输入信息格式错误，请输入正整数", "code": 401})
        # 微信支付宝时间
        now = datetime.date.today().timetuple()
        timelist = get_month_range(datetime.date(2021, 1, 1), datetime.date(now[0], now[1], now[2]))
        weixintime = timelist[:-1]
        zhifubaotime = timelist[:-1]
        weixindata = Liushui.objects.filter(weixin__isnull=False)
        for i in weixindata:
            weixintime.remove(i.month)
        zhifubaodata = Liushui.objects.filter(zhifubao__isnull=False)
        for i in zhifubaodata:
            zhifubaotime.remove(i.month)

        # 数据
        liushui = Liushui.objects.filter(user_id=user_id).order_by("-id")[:n]
        data = LiushuiSer(liushui, many=True).data
        # 统计

        end_time = str(liushui.values()[0]["month"])
        start_time = str(liushui.values()[::-1][0]["month"])
        sum_time = start_time + " -- " + end_time
        sum_zhifubao = 0
        sum_weixin = 0
        for i in liushui.values():
            if i["zhifubao"] is not None:
                sum_zhifubao += i["zhifubao"]
            if i["weixin"] is not None:
                sum_weixin += i["weixin"]

        sum_money = sum_weixin + sum_zhifubao

        # 折线图数据
        timedata = []
        for i in liushui:
            timedata.append(i.month)
        moneydata = []
        for i in liushui:
            moneydata.append(i.money)
        timedata.reverse()
        moneydata.reverse()

        return Response({"msg": "获取成功成功",
                         "code": 200,
                         "data": data,
                         "timedata":timedata,
                         "moneydata":moneydata,
                         "weixintime":weixintime,
                         "zhifubaotime":zhifubaotime,
                         "sum_time":sum_time,
                         "sum_zhifubao":sum_zhifubao,
                         "sum_weixin":sum_weixin,
                         "sum_money":sum_money,
                         })



# def adsa():
#     pass